import { Button, Input } from "@tarojs/components";
import React, { useEffect, useRef, useState } from "react";
import classNames from "classnames";
import { AtFloatLayout } from "taro-ui";

import "./index.scss";
import { instance, setStore, uploadFile } from "../../../src/utils";
import {
  CheckCheckShareInfo,
  fetchCheckFileShareInfo,
  fetchOuterMember,
  getFileUploadUrl,
  updateUser,
} from "../../../src/api";
import { IImg, ILoginResponse, IUploadResponse } from "../../../src/interfaces";
import {
  isAndroid,
  isMQQbrowser,
  isWeixin,
} from "../../../src/utils/check-browser";
import Taro, { useRouter } from "@tarojs/taro";

interface Props {
  /** 点击开始使用 */
  onStart: () => void;
}
export const RegisterCard = ({ onStart }: Props) => {
  const router = useRouter();
  const [img, setImage] = useState("");
  const [nickName, setNickName] = useState("");
  const uploadData = useRef<IUploadResponse>();
  const [open, setOpen] = useState(false);
  const handleNameInput = (e) => {
    setNickName(e.detail.value);
  };

  const handleCaptureChange = async (e: any) => {
    const [file] = e.target.files;
    Taro.showLoading();
    const { data } = await getFileUploadUrl(file.name);
    uploadData.current = data;
    uploadFile(
      file,
      data,
      (res) => {
        const { url } = data;
        setImage(url.split("?")[0] || "");
        setOpen(false);
        Taro.hideLoading();
      },
      (err) => {
        console.error("", err);
        Taro.hideLoading();
      }
    );
  };

  /** 登录逻辑 */
  const handleLogin = async (name: string, user: { img: IImg }) => {
    const phone = sessionStorage.getItem("register-phone") || "";
    const code = sessionStorage.getItem("register-code") || "";
    const body: any = {
      phoneNumber: phone,
      msgCode: "register",
      randomCode: code,
      loginType: "phoneNumberAndRandomCode",
      clientType: "web",
      invitation: true,
      nickName: name,
      user,
    };
    const referenceIdMatch = router?.params?.from?.match(/referenceId=([^&]+)/);
    if (referenceIdMatch && referenceIdMatch[1]) {
      body.referenceId = referenceIdMatch[1];
      body.invitation = true;
    }
    instance
      .post("/user/token", body)
      .then(({ data }) => data)
      .then(async ({ code: _code, data, message }) => {
        if (_code !== 0) {
          alert(message);
          return;
        }
        const { accessToken, pubKey } = data as ILoginResponse;
        setStore("token", accessToken);
        setStore("pubRsaKey", pubKey);

        if (router && router.params && router.params.from) {
          let url = router.params.from;
          if (Array.isArray(router.params.from)) {
            url = router.params.from[router.params.from.length - 1];
          }

          if (url.indexOf("project-share/index") > -1) {
            // 项目分享，校验权限、跳转
            const referenceId = router.params.from.match(/referenceId=([^&]+)/);
            const _paramPassword =
              sessionStorage.getItem("project-watch") || "";
            const _paramId = sessionStorage.getItem("project-watch-id") || "";
            const projectRes = await fetchOuterMember(_paramId, {
              password: _paramPassword,
              referenceId: (referenceId && referenceId[1]) || "",
            });
            if (projectRes.code !== 0) {
              alert(projectRes.message);
              return;
            }
            if (!projectRes.data || !projectRes.data.spaceId) {
              alert("没有空间id");
              return;
            }
            Taro.navigateTo({
              url: `/pages/index/index?spaceId=${projectRes.data.spaceId}`,
            });
          } else if (url.indexOf("file-share/index") > -1) {
            // 文件分享，校验权限、跳转
            const shareIdMatch = router.params.from.match(/shareId=([^&]+)/);
            const _paramPassword = sessionStorage.getItem("file-watch") || "";
            const fileRes = await fetchCheckFileShareInfo(
              (shareIdMatch && shareIdMatch[1]) || "",
              _paramPassword ? { password: _paramPassword } : {}
            );
            if (fileRes.code !== 0) {
              alert(fileRes.message);
              return;
            }
            const { companyId, memberType, spaceId } = data;
            if (!spaceId) {
              alert("没有空间id");
              return;
            }
            Taro.navigateTo({
              url: `/pages/file-index/index?spaceId=${spaceId}`,
            });
          } else if (url.indexOf("check-share/index") > -1) {
            // 确认分享，校验权限、跳转
            const listingIdMatch =
              router.params.from.match(/listingId=([^&]+)/);
            const listingId = (listingIdMatch && listingIdMatch[1]) || "";
            const shareIdMatch = router.params.from.match(/shareId=([^&]+)/);
            const shareId = (shareIdMatch && shareIdMatch[1]) || "";
            const _paramPassword = sessionStorage.getItem("check-watch") || "";
            const _paramId = sessionStorage.getItem("check-watch-id") || "";
            const spaceId = sessionStorage.getItem("check-spaceid") || "";
            const checkRes = await CheckCheckShareInfo(
              _paramId,
              listingId,
              shareId,
              _paramPassword ? { password: _paramPassword } : {}
            );
            if (checkRes.code !== 0) {
              alert(message);
              return;
            }
            if (!spaceId) {
              alert("没有空间id");
              return;
            }
            Taro.setStorageSync("accessKey", checkRes?.data?.accessKey);
            Taro.navigateTo({
              url: `/pages/check-index/index?spaceId=${spaceId}&shareId=${shareId}&listingId=${listingId}`,
            });
          } else {
            Taro.navigateTo({
              url: `${url}&login=true`,
            });
          }
        }
      });
    return true;
  };
  const handleStart = async () => {
    // if (!uploadData.current) return;
    const body = { img: { bucketName: "", path: "" }, nickName };
    if (uploadData.current) {
      const { bucketName, path } = uploadData.current;
      body.img.bucketName = bucketName;
      body.img.path = path;
    }
    const ret = await handleLogin(nickName, { img: body.img });
    if (ret) return;
    const { code, message } = await updateUser(body);
    if (code !== 0) {
      alert(message);
      return;
    }
    if (router && router.params && router.params.from) {
      let url = router.params.from;
      if (Array.isArray(router.params.from)) {
        url = router.params.from[router.params.from.length - 1];
      }
      Taro.navigateTo({
        url: `${url}&login=true`,
      });
    } else {
      onStart();
    }
  };

  useEffect(() => {
    const takePhotoWrapper = document.getElementById("take-photo");
    const getPhotoWrapper = document.getElementById("get-photo");
    let input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = handleCaptureChange;
    if (isAndroid() && isWeixin() && !isMQQbrowser()) {
      // 添加摄像头调用功能
      input.capture = "camera";
    }
  }, []);
  return (
    <>
      <div className="register-card">
        <div className="gretting">欢迎使用！为了方便沟通，请填写您的姓名</div>

        <div className="avatar-area">
          <div
            className="avatar"
            onClick={() => {
              setOpen(true);
            }}
          >
            {img && <img src={img} alt="" />}
            {!img && <span className="iconfont icon-gray-head"></span>}
          </div>
        </div>
        <Input
          className={classNames("name", {
            placeholder: !nickName,
          })}
          value={nickName}
          placeholder="请输入姓名"
          onInput={handleNameInput}
        ></Input>
        <Button
          disabled={!nickName}
          className={classNames("start", {
            active: !!nickName,
          })}
          onClick={(!!nickName && handleStart) || undefined}
        >
          开始使用
        </Button>
      </div>
      <AtFloatLayout
        className="register-float-layout"
        isOpened={open}
        title=""
        onClose={() => {
          setOpen(false);
        }}
      >
        <div className="file-wrapper camera" id="take-photo">
          拍摄
          <input
            type="file"
            accept="img/*"
            capture="camera"
            onChange={handleCaptureChange}
          />
        </div>
        <div className="file-wrapper photo-album" id="get-photo">
          从手机相册中选择
          <input
            accept="img/*"
            required
            type="file"
            onChange={handleCaptureChange}
          />
        </div>
        <div
          onClick={() => {
            setOpen(false);
          }}
        >
          取消
        </div>
      </AtFloatLayout>
    </>
  );
};
